<template>
  <div class="start-page">
    <div class="start-content" v-if="!showPhoneForm">
      <h1>人生事件记录</h1>
      <p>记录生命中的每一个重要时刻</p>
      <el-button 
        type="primary" 
        @click="checkUserPhone" 
        size="large"
        :loading="loading"
      >
        {{ loading ? '加载中...' : '开始使用' }}
      </el-button>
    </div>
    
    <!-- 手机号输入表单 -->
    <div class="phone-form" v-if="showPhoneForm">
      <h2>请输入手机号码</h2>
      <p>为了使用完整功能，请确认您的手机号码</p>
      
      <el-form :model="phoneForm" :rules="rules" ref="phoneFormRef" label-width="80px">
        <el-form-item label="手机号" prop="phone">
          <el-input 
            v-model="phoneForm.phone" 
            placeholder="请输入11位手机号码"
            maxlength="11"
            show-word-limit
            type="tel"
          ></el-input>
        </el-form-item>
        
        <div class="form-actions">
          <el-button @click="confirmPhone" type="primary" :loading="saving" :disabled="saving">
            确认
          </el-button>
          <el-button @click="exitApp" type="danger" :disabled="saving">
            退出应用
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { getUserInfo, getUserSettings, DEFAULT_USER_ID, updateUserInfo } from '../services/api.js'

export default {
  name: 'StartPage',
  data() {
    return {
      loading: false,
      saving: false,
      showPhoneForm: false,
      phoneForm: {
        phone: ''
      },
      rules: {
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号码', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    // 页面加载时预加载数据
    this.preloadUserData()
  },
  methods: {
    // 预加载用户数据到localStorage
    async preloadUserData() {
      try {
        // 1. 获取用户基本信息
        const userInfo = await getUserInfo()
        if (userInfo && typeof userInfo === 'object') {
          localStorage.setItem('userInfo', JSON.stringify(userInfo))
          console.log('用户信息已预加载到localStorage:', userInfo)
        }
        
        // 2. 获取用户设置
        const userSettings = await getUserSettings(DEFAULT_USER_ID)
        if (userSettings && typeof userSettings === 'object') {
          localStorage.setItem('userSettings', JSON.stringify(userSettings))
          console.log('用户设置已预加载到localStorage:', userSettings)
        }
      } catch (error) {
        console.error('预加载用户数据失败:', error)
      }
    },
    
    // 检查用户是否有手机号
    async checkUserPhone() {
      this.loading = true
      try {
        // 获取用户信息
        const userInfo = await getUserInfo()
        
        // 如果用户没有手机号或者手机号为空，显示手机号输入表单
        if (!userInfo || !userInfo.phone || userInfo.phone.trim() === '') {
          this.showPhoneForm = true
        } else {
          // 如果用户已有手机号，直接跳转到首页
          this.$router.push('/home')
        }
      } catch (error) {
        console.error('检查用户信息失败:', error)
        // 出错时也显示手机号输入表单
        this.showPhoneForm = true
      } finally {
        this.loading = false
      }
    },
    
    // 确认手机号
    async confirmPhone() {
      // 验证表单
      this.$refs.phoneFormRef.validate(async (valid) => {
        if (valid) {
          this.saving = true
          try {
            // 获取当前用户信息
            const userInfo = await getUserInfo()
            
            // 更新用户信息，保存手机号
            await updateUserInfo(
              userInfo ? userInfo.username : '默认用户',
              userInfo ? userInfo.avatar : null,
              this.phoneForm.phone
            )
            
            // 更新localStorage中的用户信息
            const updatedUserInfo = { ...userInfo, phone: this.phoneForm.phone }
            localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo))
            
            // 跳转到首页
            this.$router.push('/home')
          } catch (error) {
            console.error('保存手机号失败:', error)
            this.$message.error('保存失败，请重试')
          } finally {
            this.saving = false
          }
        }
      })
    },
    
    // 退出应用
    exitApp() {
      this.$confirm('确定要退出应用吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 在移动设备上退出应用的方法
        if (window.__TAURI__) {
          window.__TAURI__.process.exit(0)
        } else {
          // Web环境下的处理，刷新页面或提示用户关闭窗口
          alert('请关闭此窗口')
        }
      }).catch(() => {
        // 用户取消退出
      })
    }
  }
}
</script>

<style scoped>
.start-page {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 1rem;
  padding-bottom: 60px;
}

.start-content {
  text-align: center;
  color: white;
  padding: 2rem;
  width: 100%;
  max-width: 400px;
}

.start-content h1 {
  font-size: 2.5rem;
  margin-bottom: 1rem;
  font-weight: bold;
}

.start-content p {
  font-size: 1.2rem;
  margin-bottom: 2rem;
  opacity: 0.9;
}

.phone-form {
  background: white;
  border-radius: 12px;
  padding: 2rem;
  width: 100%;
  max-width: 400px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.phone-form h2 {
  color: #303133;
  text-align: center;
  margin-bottom: 0.5rem;
  font-size: 1.8rem;
}

.phone-form p {
  color: #606266;
  text-align: center;
  margin-bottom: 2rem;
  font-size: 1rem;
}

.form-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 1.5rem;
}

.form-actions .el-button {
  flex: 1;
  margin: 0 0.5rem;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .start-content,
  .phone-form {
    padding: 1.5rem;
  }
  
  .start-content h1 {
    font-size: 2rem;
  }
  
  .phone-form h2 {
    font-size: 1.5rem;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .form-actions .el-button {
    margin: 0.5rem 0;
  }
}
</style>